package com.hangxintong.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hangxintong.common.SnowflakeIdWorker;
import com.hangxintong.common.StatusCode;
import com.hangxintong.common.base.dto.MessageDTO;
import com.hangxintong.common.base.entity.LmUser;
import com.hangxintong.common.base.entity.UserRepository;
import com.hangxintong.common.exception.SystemException;
import com.hangxintong.common.exception.SystemErrorCodeMark;
import com.hangxintong.common.utils.Result;
import com.hangxintong.jpa.InformationRepository;
import com.hangxintong.jpa.LmInformation;
import com.hangxintong.common.base.dto.MessageFiles;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Lenovo
 */
@Service
@Slf4j
public class InformationService {

    @Resource
    InformationRepository informationRepository;
    @Resource
    UserRepository userRepository;
    @Resource
    SnowflakeIdWorker snowflakeIdWorker;
    @Resource
    MsgQueueService msgQueueService;


    /**
    * @Description
    * @Author  Bz.Mr
    * @Date   2020/12/11 17:46
    *
    */
    public Result add(HttpServletRequest request, MessageDTO messageDTO) throws Exception{
        LmUser user = (LmUser) request.getAttribute("user");
        if (StringUtils.isEmpty(messageDTO.getTitle())) return new Result(false, StatusCode.ERROR, "标题必填");
        if (StringUtils.isEmpty(messageDTO.getText())) return new Result(false, StatusCode.ERROR, "内容必填");
        if (StringUtils.isEmpty(messageDTO.getSjrId())) return new Result(false, StatusCode.ERROR, "收件人必填");
        LmInformation lmInformation = new LmInformation();
        if (StringUtils.isEmpty(messageDTO.getId())) {
            lmInformation.setId(snowflakeIdWorker.nextIdStr());
            //判断是否有fjrid 和 fjr名称
            if(messageDTO.getFjrId()==null||messageDTO.getFjrId()<1){
                lmInformation.setFjrId(user.getId().intValue());
                lmInformation.setFjrName(user.getRealname());
            }else{
                lmInformation.setFjrId(messageDTO.getFjrId());
                lmInformation.setFjrName(messageDTO.getFjrName());
            }

            lmInformation.setCreateTime(Result.getTime());
        } else {
            lmInformation = informationRepository.findById(messageDTO.getId()).orElseThrow(()->new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST,"消息数据不存在！"));
        }

        lmInformation.setTitle(messageDTO.getTitle());
        lmInformation.setText(messageDTO.getText());

        LmUser sjr = userRepository.findById(Long.valueOf(messageDTO.getSjrId())).orElseThrow(()->new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST,"用户不存在"));

        lmInformation.setSjrId(messageDTO.getSjrId());
        lmInformation.setCate(messageDTO.getCate());
        lmInformation.setSjrName(sjr.getRealname());
        lmInformation.setFiles(JSON.toJSONString(messageDTO.getFiles()));
        lmInformation.setParames(JSON.toJSONString(messageDTO.getParames()));
        lmInformation.setPid(messageDTO.getPid());
        lmInformation.setIsReply(messageDTO.getIsReply());
//        lmInformation.setCreateId(user.getId().toString());
        lmInformation.setCreateId("1");
        lmInformation.setUtype(messageDTO.getUtype());

        LmInformation save = informationRepository.save(lmInformation);

        return Result.ok(save);
    }

    public Result del(HttpServletRequest request, String id) {
        LmUser user = (LmUser) request.getAttribute("user");
        if (id == null) return new Result(false, StatusCode.ERROR, "id必填");
        LmInformation arr = informationRepository.findById(id).orElseThrow(()->new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST,"系统消息"));
        arr.setIsDelete(user.getId().intValue());
        arr.setDeleteTime(Result.getTime());
        informationRepository.save(arr);
        return new Result(true, StatusCode.OK, "操作成功", arr);
    }

    public Result updateInfoStatus(HttpServletRequest request, String id) {
        LmUser user = (LmUser) request.getAttribute("user");
        if (id == null) return new Result(false, StatusCode.ERROR, "id必填");
        LmInformation arr = informationRepository.findById(id).orElseThrow(()->new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST,"消息数据不存在~"));
        //催费信息更新为已读
        if(arr.getCate()==5){
//            HashMap<String, String> hasMap = new HashMap<>();
//            JSONObject.parse(arr.getParames())
//            msgQueueService.sendMembership();
        }
        arr.setStatus(2);
        informationRepository.save(arr);
        return new Result(true, StatusCode.OK, "操作成功", arr);
    }

    public Result findInfo(String id) {
        LmInformation one = informationRepository.findById(id).orElseThrow(()->new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST,"消息数据不存在~"));
        if(one!=null) {
            List<MessageFiles> messageFiles = JSON.parseArray(one.getFiles(), MessageFiles.class);
            one.setListFiles(messageFiles);
        }
        return new Result(true, StatusCode.OK, "操作成功", one);
    }

    public Page<LmInformation> pagelist(Integer status, Integer cate, Integer page, Integer size, LmUser user, String search) {
        Pageable pageable = PageRequest.of(page - 1, size, Sort.Direction.DESC, "sort");
        Page<LmInformation> bookPage = informationRepository.findAll(new Specification<LmInformation>() {
            @Override
            public Predicate toPredicate(Root<LmInformation> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                // 开始or查询
                List<Predicate> list = new ArrayList<Predicate>();
                if (null != search && !"".equals(search)) {
                    list.add(criteriaBuilder.like(root.get("title").as(String.class), "%" + search + "%"));
                }
                if (null != search && !"".equals(search)) {
                    list.add(criteriaBuilder.like(root.get("text").as(String.class), "%" + search + "%"));
                }
                Predicate or = criteriaBuilder.or(list.toArray(new Predicate[list.size()]));
                or = criteriaBuilder.and(or);
                // 开始and查询
                List<Predicate> listAnd = new ArrayList<Predicate>();
                if (null != status && !"".equals(status)) {
                    listAnd.add(criteriaBuilder.equal(root.get("status").as(String.class), status));
                }
                if (null != cate && !"".equals(cate)) {
                    listAnd.add(criteriaBuilder.equal(root.get("cate").as(String.class), cate));
                }
                listAnd.add(criteriaBuilder.equal(root.get("sjrId").as(String.class), user.getId()));
                Predicate and = criteriaBuilder.and(listAnd.toArray(new Predicate[listAnd.size()]));
                //return query.where(or,and).getRestriction();
                if (list == null || list.isEmpty()) {
                    return query.where(and).getRestriction();
                }else {
                    return query.where(or, and).getRestriction();
                }
            }
        }, pageable);
        //处理files
        if(bookPage.hasContent()){
           bookPage.getContent().forEach(msg->{
               List<MessageFiles> messageFiles = JSON.parseArray(msg.getFiles(), MessageFiles.class);
               msg.setListFiles(messageFiles);
           });
        }
        return bookPage;
    }
    /**
    * @Description
    * @Author  Bz.Mr
    * @Date   2021/1/12 18:41
    * 显示某条消息下回复的内容
    */
    public List<LmInformation> listReplyMessage(int userId, String id) {

        //1、查询消息数据
        LmInformation lmInformation = informationRepository.findById(id).orElseThrow(()->new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST,"消息数据不存在~"));

        //LmInformation one = informationRepository.findById(id).orElseThrow(()->new SystemException(SystemErrorCodeMark.Code.INFO_DATA_NOT_EXIST));
        //2、查询当前用户回复记录
        List<LmInformation> listInfos= informationRepository.findByPidAndFjrId(lmInformation.getId(),lmInformation.getSjrId());
        if(listInfos.size()>0) {
            listInfos.forEach(msg -> {
                List<MessageFiles> messageFiles = JSON.parseArray(msg.getFiles(), MessageFiles.class);
                msg.setListFiles(messageFiles);
            });
        }
        return listInfos;
    }
    /**
    * @Description
    * @Author  Bz.Mr
    * @Date   2021/1/13 9:14
    * 查看回复消息
    */
    public Page<LmInformation> listMessages(String id,PageRequest pageRequest) {
        //1、查询消息数据
        LmInformation lmInformation = informationRepository.findById(id).orElseThrow(() -> new SystemException(SystemErrorCodeMark.Code.INFO_DATA_NOT_EXIST));
        //2、查询当前用户回复记录
        Page<LmInformation> listInfos= informationRepository.findByPid(lmInformation.getId(),pageRequest);
        if(listInfos.hasContent()){
            listInfos.getContent().forEach(msg->{
                List<MessageFiles> messageFiles = JSON.parseArray(msg.getFiles(), MessageFiles.class);
                msg.setListFiles(messageFiles);
            });
        }
        return listInfos;
    }
}
